<?php

class ApplesController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('test','sendstat','stat','json','last','init','send'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('index','view','admin','group','map'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('create','update','delete','bat','check'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * ################################################################################################
	 * ################################################################################################
	 * ################################################################################################
	 * 
	 * 返回初始化的json变量
	 * 
	 */
	public function actionInit()
	{ 
		$ret = array(
			"sendout"=> "6",
			"checkout"=> "3" ,
			"waittime"=> "10",

			"reloginout"=> "500",
			"relogintime"=> "300",
		);
		echo json_encode($ret);
		// set SEND_OUT to sendout of (init_info & {sendout:5})
		// set CHECK_OUT to checkout of (init_info & {checkout:5})
		// set WAIT_TIME to waittime of (init_info & {waittime:20})
		// set RELOGIN_OUT to reloginout of (init_info & {reloginout:30})
		// set RELOGIN_TIME to relogintime of (init_info & {relogintime:10 * 60})

		Yii::app()->end();
	}
	/**
	 * 检查状态，并发送邮件
	 * @return [type] [description]
	 */
	public function actionSend()
	{
		$robots = Robot::model()->findAll();
		$message = "";
		$indexs = 0;
		foreach($robots as $r){
			if(strpos($r->name , 'tuixin') !== false){
				if(ceil((time() - strtotime($r->lasttime))/60) > 30){
					$message .= "机器【".$r->name."】已经离线，最后登录于".$r->lasttime."。\n";
					$indexs++;
				}
			}
		}

		$subject = $indexs."台客户端离线，请检查。";

		echo $subject.$message;
		if($indexs > 0){

			$message .= "\n详情点击查看：http://sim.appmars.com/sim/index.php?r=robot/admin";
			$message .= "\n\n\n苹果推信v2.3";
			$message .= "\n北京扬仁网络科技有限公司";
			$message .= "\n地址：北京市朝阳区建国路88号SOHO现代城3号楼3102";
			$message .= "\n电话：4000-789-360 010-58203300-7020 010-52908090";
			$message .= "\n网站：http://tuixin.mobi";
			Yii::app()->mailer->CharSet = "UTF-8";
			Yii::app()->mailer->SMTPAuth = true; 
			Yii::app()->mailer->Host = 'smtp.qq.com';
			Yii::app()->mailer->Username = "bourneliu83@qq.com"; 
			Yii::app()->mailer->Password = "1qazxsw2"; 
			Yii::app()->mailer->IsSMTP();
			Yii::app()->mailer->Port=25; 
			Yii::app()->mailer->From = 'bourneliu83@qq.com';
			Yii::app()->mailer->FromName = 'bourneliu83@qq.com';
			// Yii::app()->mailer->AddReplyTo('wei@pradosoft.com');
			Yii::app()->mailer->AddAddress('romejiang@qq.com');
			// Yii::app()->mailer->IsHTML(true);
			Yii::app()->mailer->Subject = $subject;
			Yii::app()->mailer->Body = $message;
			

			if(Yii::app()->mailer->Send())
			{
				echo 'send ok';
			}else{
				echo 'send error';
			}
		}

		Yii::app()->end();
	}
/**
	 * 更新一条信息的状态
	 *  0,初始化，1，正在扫描，2，成功，3，失败	 
	 */
	public function actionSendstat($id,$stat)
	{
		$tasking = Tasking::model()->find("appleid=:id", array(':id'=>$id));
		 
		if($tasking !== null){

		 	$model=new Tasklog;
			$model->appleid = $id;
			$model->taskid = $tasking->taskid;
			$model->stat = $stat;
			
			if($stat === '2'){
				$task = Task::model()->find("id=:id" , array(':id'=>$tasking->taskid));
				$task->sendtoday++;
				$task->save();
			}
			$tasking->delete();
			if($model->save()){
				echo '{"message": "save succeed"}';
			}else{
				echo '{"message": "save failure"}';
			}
		}else{
			echo '{"message": "Not found taskid"}';
		}
		Yii::app()->end();
	}
	/**
	 * 更新一条信息的状态
	 *  0,初始化，1，正在扫描，2，成功，3，失败	 
	 */
	public function actionStat($id,$stat)
	{
		if($stat==="2"){
			$model = Apples::model()->find("appleid=:ap" , array(':ap'=>$id));
			if($model===null){
				$model=new Apples;
				$model->appleid = $id;
				$model->name = $id;
				$area = $this->getMobileArea($id);
				if($area !== ""){
					$model->province = substr($area, 0, strpos($area, " "));//strstr($area," ",true);
					$model->city = strstr($area," ");;
				}
			}
			$model->stat = 2;
			$model->save();
			echo '{"message": "check"}';
		}
			 
		// 	$model=Task::model()->findByPk($taskid);
		// 	if(!($model === null) and ($stat === "1")){
		// 		if(0 != strcmp($model->district,'test')){
		// 			$model->sendtoday++;
		// 			$model->save();
		// 		}
		// 		echo '{"message": "send"}';
		// 	}
		// }
		
		Yii::app()->end();
	}
	/**
	 * 根据手机号码，判断地区
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	private function getMobileArea($id){
		if(strlen($id) === 11){
			$area = substr($id,0,7);
			// echo $area;
			$value = Yii::app()->cache->get($area);  
			if($value===false)  
			{  
				// echo "find db".$area;
			    $mArea = Mobile::model()->find("mobile=:name" , array(':name'=>$area));
			    if($mArea !== null){
			    	$value = $mArea->area;
			    	Yii::app()->cache->set($area , $value , 60 * 60 );
			    }else{
			    	return "";
			    }
			} 
			return $value;
		}
		return "";
	}
	/**
	 *  * 
	 *  批量更新 apples 状态为初始状态， 0,初始化，1，正在扫描，2，成功，3，失败	 
	 * @param  [type] $start [description]
	 * @return [type]        [description]
	 */
	public function actionCheck($start)
	{
		$apps = Apples::model()->updateAll(array('stat'=>0), "stat=:stat" , array(':stat'=>$start));

		// var_dump($ret);
		echo "update to ".$apps;
		Yii::app()->end();
	}
	/**
	 * 获得最新的登录用户账号信息
	 * 
	 */
	// public function actionLast()
	// {
	// 	$apps = Account::model()->find( array('order'=>'timetoday asc'));
	// 	//echo time();
	// 	$apps->timetoday = time();

		
	// 	$ret = array("un" => $apps->name , 'pw'=>$apps->password , 'tt'=>$apps->timetoday );

	// 	$apps->save();
	// 	// var_dump($ret);
	// 	echo json_encode($ret);
	// 	Yii::app()->end();
	// }
	public function actionTest($robot){
		 
		$apps = Apples::model()->findAll("stat=2 order by id desc limit 30");
		
		$ret = array();  
		foreach($apps as $v)
		{
		   $ret[] = array("appleid" => $v['appleid']);
		   //array_push($ret , array("appleid" => $v['appleid']));
		   //$v->stat = 1;
		   //$v->save();
		}
		 
		// $robot->stat += count($apps);
		echo json_encode(array('cmd'=> "check", 'params'=>'', 'dataarea'=>$ret));

		
	}
	/**
	 * 根据机器，获得任务信息
	 * 300 是默认，无任务
	 * 301 没有号码
	 * 302 完成发送任务
	 * @param  [type] $robot [description]
	 * @return [type]        [description]
	 */
	public function actionJson($robot)
	{
		$reloginout = 500;    // 发送500条，等待一会
		$relogintime = 180;  // 发送等待时间
		$limitout = 50;		//每次返回条数
		
		//1.获得机器,并更新最新更新时间
		$model = Robot::model()->find("name=:name" , array(':name'=>$robot));
		if(empty($model)){
			$model=new Robot;
			$model->stat = 0;
			$model->name = $robot;

		}
		$model->lasttime = date('Y-m-d H:i:s');
		$model->save();

		//2.并查询相关任务，
		//2.有任务就组织任务
		//3，没任务就sleep
		//echo $model->taskid;
		if($model->taskid == 0){
			$this->sleep();
			return;
		}else{
			$task = Task::model()->find("id=:id" , array(':id'=>$model->taskid));
			
			$cmd = $task->name;
			$content = $task->content;
			$district = $task->district;
		}
		if ($cmd === "sleep"){ // 等待
			$this->sleep();
			return;
		}
		// 发送或扫描太多，休息一会。
		if($model->stat > $reloginout){
			$model->stat = 0;
			$model->save();
			ApplesController::sleep($relogintime);
			return;
		}
		
		// ===========================================================
		// ===========================================================
		if($cmd === "check"){ // 扫描
			if($this->standbyCheck($district , $limitout , $model)){
				$this->check($district , $limitout , $model);
			} //如果备份池里没有，就取群发池
		} 

		if ($cmd === "send"){
			// 发送任务完成了
			if($task->sendtoday >= $task->sendofmax ){
				$this->check('all' , $limitout , $model);
				return;
			}

			if($district === 'all'){
				$apps = Apples::model()->findAll("stat=2 order by id desc limit ".$task->toindex.",".$limitout);
			}else{
				$apps = Apples::model()->findAll(" province='".$district."' and stat=2 order by id desc limit ".$task->toindex.",".$limitout);
			}

			$ret = array();
			foreach($apps as $v)
			{
				$ret[] = array("appleid" => $v['appleid']);
				$tasking = new Tasking;
				$tasking->taskid = $task->id;
				$tasking->appleid = $v['appleid'];
				$tasking->save();
			}
			if(empty($ret)){
				ApplesController::sleep(404);
			}
			// if(0 != strcmp($district,'test')){
			$task->toindex += count($apps);
			$model->stat += count($apps);
			// }
			$task->save();
			echo json_encode(array('cmd'=> $cmd, 'tid'=> $task->id,
				'params'=> $content, 'dataarea'=>$ret));
		}  
		
		$model->save();
		//Yii::app()->end();
	}
	/**
	 * 扫描备用号码池
	 * @param  [type] $district [description]
	 * @param  [type] $limitout [description]
	 * @param  [type] $robot    [description]
	 * @return [type]           [description]
	 */
	private function standbyCheck($district,$limitout,$robot){

		if($district === 'all'){
		   $apps = Mailid::model()->findAll(" stat=0 order by id desc limit ".$limitout);
		}else{
		   $apps = Mailid::model()->findAll(" province='".$district."' and stat=0 order by id desc limit ".$limitout);
		}

		$ret = array();  
		foreach($apps as $v)
		{
		   $ret[] = array("appleid" => $v['appleid']);
		   //array_push($ret , array("appleid" => $v['appleid']));
		   $v->stat = 1;
		   $v->save();
		}
		if(empty($ret)){
			return true;
		}else{
			$robot->stat += count($apps);
			echo json_encode(array('cmd'=> "check", 'params'=>'', 'dataarea'=>$ret));
			return false;
		}
	}
	/**
	 * 私有方法，返回扫描数据
	 * @param  [type] $district [description]
	 * @param  [type] $limitout [description]
	 * @param  [type] $model    [description]
	 * @return [type]           [description]
	 */
	private function check($district,$limitout,$model){
		if($district === 'all'){
			$mobile = Mobile::model()->find(" 1=1 order by times , postion desc");
		}else{
			$mobile = Mobile::model()->find(" area like '%".$district."%' order by times , postion desc");
		}
		$ret = array(); 
		if($mobile !== null){

			$seed = $mobile->postion;
			$mobilearea = $mobile->mobile;

			// echo $seed . $mobilearea;

			$max = ($seed + $limitout) > 9999 ? 9999 : $seed + $limitout;
			 

			for($i = $seed; $i <= $max ; $i++)
			{
				// $model=new Apples;
				$appid = $mobilearea. sprintf("%04d", $i);
				// echo $appid."<br>";
				$ret[] = array("appleid" => $appid);
			}
			if($max >= 9999){
		 		$mobile->postion = 0;
				$mobile->times++;
			}else{
				$mobile->postion = $max;
			}
			$mobile->save();
		}

		if(empty($ret)){
			ApplesController::sleep(404);
		}

		$model->stat += count($ret);
		echo json_encode(array('cmd'=> 'check' , 'params'=>'', 'dataarea'=>$ret));
		
	}
	/**
	 * 私有方法，返回默认的等待任务
	 * @return [type] [description]
	 */
	private function sleep($timeouts = 300){
		echo json_encode(array('cmd'=> 'sleep', 'params'=> $timeouts, 'dataarea'=>''));
		Yii::app()->end();
	}
	/**
	 * 批量添加 apples 
	 * @param  [type] $start [description]
	 * @return [type]        [description]
	 */
	public function actionBat($start)
	{
		// echo $start;
		$i=999;
		while($i > 0)
		{
			$model=new Apples;
			$appid = $start. sprintf("%04d", $i);
			echo $appid."<br>";
			$model->appleid = $appid;
			$model->name = $appid;
			$model->stat = 0;
			// var_dump($model);
			echo $model->save();
			$i--;

		}
		Yii::app()->end();
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		// if(isset($_POST['Apples']))
		// {
		// 	$model->attributes=$_POST['Apples'];
		// 	if($model->save())
		// 		$this->redirect(array('view','id'=>$model->id));
		// }

		// $this->render('create',array(
		// 	'model'=>$model,
		// ));
	}
	/**
	 * ################################################################################################
	 * ################################################################################################
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		header("Content-type: text/html; charset=utf-8");
		$model=new Apples;
		$model->stat = 2;
		 
		if(isset($_POST['Apples']))
		{ 
			$count = 0;
			$start = $_POST['Apples']['appleid'];
			//echo $start;
			$apples = (split("\n" , $start ));
			foreach ($apples as $key ) {
				if(strlen($key)===11){

					// echo $key."<br>";
					$model=new Apples;
					$model->attributes=$_POST['Apples'];
					
					$model->appleid = $key;
					
					$model->save();
					$count--;
				 
				}
			}
			// return;
			// $this->redirect(array('apples/admin'));
			echo "已加入".$count."条号码!<br>";
			echo "<a href='".$this->createUrl('apples/create')."'>继续添加</a><br>";
			echo "或者<a href='".$this->createUrl('apples/admin')."'>进入号码池查看</a><br>";
			Yii::app()->end();
			 
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Apples']))
		{
			$model->attributes=$_POST['Apples'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Apples');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Apples('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Apples']))
			$model->attributes=$_GET['Apples'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	/**
	 * 号码统计.
	 */
	public function actionGroup($save=0)
	{
		$filename = Yii::app()->basePath."/apples-group.json";
		//echo $filename;
		if(($save != 0) or (!file_exists($filename))){
			echo "refresh data...";
			$model = array();

			$city = Globals::province();
			foreach ($city as $province) {
				# code...
				// $province = $value['mName'];
				$count =  Apples::model()->count("stat=2 and province=:tid" , array(':tid'=>$province));
				$model[$province] =$count;
				//echo $province .$count."<br>";
			}

			file_put_contents($filename, json_encode($model));
		}else{
			$model = json_decode(file_get_contents($filename));
		}

		//var_dump($model);
		$this->render('group',array(
			'model'=>$model,
		));
	}

	public function actionMap()
	{
		$filename = Yii::app()->basePath."/apples-group.json";
		//echo $filename;
		$maxid = Mobile::model()->count();
		$nowid = Apples::model()->count();
		 
		 
		if(file_exists($filename)){
			$model = json_decode(file_get_contents($filename));
		}

		//var_dump($model);
		$this->render('map',array(
			'model'=>$model,'maxid'=> $maxid*10000, 'nowid'=> $nowid
		));
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Apples the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Apples::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Apples $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='apples-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
